import onewayHtml from 'ngtemplate!html!../../../tpls/realtime/oneway.tpl.html';
import circleHtml from 'ngtemplate!html!../../../tpls/realtime/circle.tpl.html';
import teamHtml   from 'ngtemplate!html!../../../tpls/realtime/team.tpl.html';
import validHtml from 'ngtemplate!html!../../../tpls/dialog/valid.dialog.html';

class RealtimeListController {
    constructor($rootScope, $scope, $cookieStore, $timeout, $state, $filter, ngDialog, tableService, dialogService, ScoreService, getRaceDetail, getCourseList, iRunner){

        var vm = this;

        vm.$rootScope    = $rootScope;
        vm.$cookieStore  = $cookieStore;
        vm.$timeout      = $timeout;
        vm.$state        = $state;
        vm.$filter       = $filter;
        vm.getRaceDetail = getRaceDetail;
        vm.ngDialog      = ngDialog;
        vm.tableService  = tableService;
        vm.dialogService = dialogService;
        vm.ScoreService  = ScoreService;
        vm.getCourseList = getCourseList;
        vm.iRunner       = iRunner;

        vm.teamlist    = [];
        vm.realtime    = [];
        vm.course      = '';
        vm.show        = true;
        vm.show_select = true;
        vm.cp          = '';

        //保存事实成绩页面
        vm.$rootScope.realtimeList = [];

        // 成绩查询模版
        vm.templateUrl = [
            {
                'course_type': 'oneway',
                'tpl': onewayHtml
            },
            {
                'course_type': 'custom',
                'tpl': onewayHtml
            },
            {
                'course_type': 'circle',
                'tpl': circleHtml
            }
        ];

        // 默认模版
        vm.template = vm.templateUrl[0]['tpl'];

        // tabs
        vm.tabs = [];

        // 科目列表
        if (vm.getCourseList.code==0) {

            vm.courselist = vm.getCourseList.data;

            // 科目不为空, 默认选中第一个并显示全体成绩
            if (vm.courselist.length>0) {
                vm.course = vm.courselist[0];
                vm.show   = true;
            } else {
                vm.show   = false;
            }
        } 

        // 监听科目变化
        $scope.$watch(angular.bind(vm, () => vm.course), (newValue, oldValue) => {
            if (newValue) {

                vm.show_select = true;

                vm.$timeout( () =>　{ vm.tabs = [] }, 0)
                vm.$timeout( () =>　{ vm.tabs = newValue.score_show }, 0)

                console.log(newValue)
                //保存当前科目名称
                vm.crouseState = newValue;
            } else if (newValue == undefined) {
                vm.realtime    = [];
                vm.show        = false;
                vm.show_select = true;
            }
        });

        // 监听模型变化, 获取相应的数据
        $scope.$watch(angular.bind(vm, () => vm.tabs.activeTab), (newValue, oldValue) => {

            if (newValue) {

                // 未选择科目直接return
                if (!vm.course) {
                    !vm.show&&$.blink(angular.element(document.getElementsByName('course')), 5, 100)
                    return false;
                }

                // 根据选中Tab获取相应数据
                angular.forEach(vm.tabs, (value, index) => {
                    if (value.title == newValue) {

                        vm.$timeout( () => { vm.template = '' }, 0);

                        vm.$timeout( () => { 

                            // 判断非团队, 配置对应模版
                            if (vm.course && vm.course.dist_team == 'no') { 
                                vm.templateFn()
                            }

                            // 判断团队, 配置对应模版
                            if (vm.course && vm.course.dist_team == 'yes') {
                                vm.teamTplFn(value.type)
                            }

                        }, 0);

                        vm.$timeout( () => {

                            // 判断非团队
                            if(vm.course && vm.course.dist_team == 'no') {
                                vm.realtimeFn(value.type);
                                //保存当前性别
                                vm.sexfortable = value.type;
                            }

                            // 判断团队
                            if (vm.course && vm.course.dist_team == 'yes') {
                                vm.realtimeTeamFn(value.type)
                                //保存当前性别
                                vm.sexfortable = value.type;
                            }
                        }, 0)
                    }
                });

                console.log(newValue)
            }

        });
        
        /**
         * 选手搜索
         * @param  {[type]} bib [description]
         * @return {[type]}     [description]
         */
        vm.search = function(bib) {
            //未输入选手号的场合
            if (!bib) {
                vm.dialogService.error("请输入选手号，再进行搜索。");
            } else {

                vm.dialogService.error("敬请期待");
                //TODO
                // var data = {
                //     course_id: 242,
                //     runner_id: 236753
                // };
                // //跳转个人成绩页面
                // vm.$state.go('dashboard.race.realtimerunner', data);
            }
        }

        /**
         * 打印实时页面成绩
         * @return {[type]} [description]
         */
        vm.print = function() {
            //存储数据到Local storage
            var obj = {
                race_name: vm.getRaceDetail.data.disp_name,
                course_name: vm.crouseState.course_name,
                realtimeData: vm.$rootScope.realtimeData
            }
            localStorage.setItem('realtimeDataForPrintOld', JSON.stringify(obj));
            
            //打开打印页面
            window.open("tpls/realtime/print.html");
        }

        /**
         * 下载成绩
         * @return {[type]} [description]
         */
        vm.download = function() {
            //下载成绩链接
            vm.window = window.open("/dashboard/realtime/download?course_id=" + vm.course.course_id + "&access-token=" + this.$cookieStore.get('access_token'));                 
        }

        /**
         * 投影大屏幕按钮
         */
        vm.largeScreen = function () {
            console.log(location.host + '/dashboard/realtime/lists?race_id=' + vm.$state.params.race_id + '&course_id=' + vm.course.course_id + '&genderby=' + vm.sexfortable + '&access-token=' + this.$cookieStore.get('access_token'));
            console.log(vm.getRaceDetail.data.disp_name);
            console.log(vm.crouseState.course_name);
            var obj = {
                url: '/dashboard/realtime/lists?race_id=' + vm.$state.params.race_id + '&course_id=' + vm.course.course_id + '&genderby=' + vm.sexfortable + '&access-token=' + this.$cookieStore.get('access_token'),
                race_name: vm.getRaceDetail.data.disp_name,
                course_name: vm.crouseState.course_name,
                sex: vm.sexfortable
            }
            //存储数据到Local storage
            localStorage.setItem('dataForScreen', JSON.stringify(obj));
            //打开大屏幕
            window.open('tpls/realtime/screen.html');
        }
    
        /**
         * 监听模型变化, 获取相应的数据
         * @param  {[type]} angular.bind(vm, ()            [description]
         * @param  {[type]} (newValue,       oldValue      [description]
         * @return {[type]}                  [description]
         */
        $scope.$watch(angular.bind(vm, () => vm.cp), (newValue, oldValue) => {
            if (newValue) {
                //选择cp点的场合
                vm.course && vm.tableSearchFn(newValue.cp_index);
                console.log(newValue);

            } else {
                //全部cp点的场合
                vm.course && vm.tableSearchFn();
            }
        })

        /**
         * 发布成绩
         */
        vm.publish = function() {

            // 模态框显示文本
            $rootScope.common = {
                text : '是否发布成绩'
            }

            vm.ngDialog.open({
                template: validHtml,
                className: 'ngdialog-theme-default ngdialog-alert',
                scope: $scope
            });


            $rootScope.submitDelForm = (isValid) => {
                if (!isValid) {
                    vm.dialogService.error();
                }

                if (isValid) {

                    // 关闭模态框
                    vm.ngDialog.close();
                    // 显示进度条
                    $rootScope.progressBar = true;


                    var status = '', start = '', total = '';
                    // 完结时间
                    var dueTime = '--';

                    // 重新计算所有成绩（调用后台接口）
                    var importStart = (status, start, total) => {
                        vm.ScoreService.getRealtimeScorePublish(vm.$cookieStore.get('access_token'), vm.$state.params.race_id + '&start=' + start)
                        .then( data => {
                            console.log(data);
                            if (data.code == 0) {

                                status = data.data.status;
                                start = data.data.current;
                                total = data.data.total;

                                //设置进度条百分比
                                $rootScope.progress =  parseInt(start/total*100) + '%';
                                //总条数
                                $rootScope.total = total;
                                //完结条数
                                $rootScope.begin = start;
                                // 完结时间（耗时）
                                $rootScope.dueTime = parseInt((total-start)/4) + '秒';


                                if (status == 'continue') {
                                    importStart(status, start, total);                        
                                } else if (status == 'done') {
                                    $rootScope.progressBar = false;
                                    return;
                                }

                            } else {
                                vm.dialogService.error(data.message);
                            }

                        }, error => {
                            vm.dialogService.error("计算失败");
                            console.log('error')
                        });
                    }

                    importStart(status, start, total);

                }
                console.log('重新计算所有成绩')
                return false;
            }
        }

        /**
         * 重新计算所有成绩
         * @return {[type]} [description]
         */
        vm.recalc = function() {

            // 模态框显示文本
            $rootScope.common = {
                text : '您要重新计算所有选手的成绩吗？这将耗费数分钟或更长时间'
            }

            vm.ngDialog.open({
                template: validHtml,
                className: 'ngdialog-theme-default ngdialog-alert',
                scope: $scope
            });

 

            $rootScope.submitDelForm = (isValid) => {
                if (!isValid) {
                    vm.dialogService.error();
                }

                if (isValid) {

                    // 关闭模态框
                    vm.ngDialog.close();
                    // 显示进度条
                    $rootScope.progressBar = true;


                    var status = '', start = '', total = '';
                    // 完结时间
                    var dueTime = '--';

                    // 重新计算所有成绩（调用后台接口）
                    var importStart = (status, start, total) => {
                        vm.ScoreService.getRealtimeScorecalc(vm.$cookieStore.get('access_token'), vm.$state.params.race_id + '&start=' + start)
                        .then( data => {
                            console.log(data);
                            if (data.code == 0) {

                                status = data.data.status;
                                start = data.data.current;
                                total = data.data.total;

                                //设置进度条百分比
                                $rootScope.progress =  parseInt(start/total*100) + '%';
                                //总条数
                                $rootScope.total = total;
                                //完结条数
                                $rootScope.begin = start;
                                // 完结时间（耗时）
                                $rootScope.dueTime = parseInt((total-start)/4) + '秒';


                                if (status == 'continue') {
                                    importStart(status, start, total);
                                } else if (status == 'done') {
                                    $rootScope.progressBar = false;
                                    return;
                                }

                            } else {
                                vm.dialogService.error(data.message);
                            }

                        }, error => {
                            vm.dialogService.error("计算失败");
                            console.log('error')
                        });
                    }

                    importStart(status, start, total);

                }
                console.log('重新计算所有成绩')
                return false;
            }  
        }

    }

    /**
     * 判断非团队, 配置对应模版
     * @return {[type]} [description]
     */
    templateFn() { 
        angular.forEach(this.templateUrl, (value, index) => (value.course_type == this.course.course_type) && (this.template = value.tpl))
    }

    // 判断团队, 调用个人接口或团队接口
    realtimeTeamFn(value) {
        if (value.indexOf('team')==-1) {
            this.realtimeFn(value)
        } else {
            this.distTeamFn(value.substr(5));
        }
    }

    /**
     * 判断团队, 配置对应模版
     * @param  {[type]} value [description]
     * @return {[type]}       [description]
     */
    teamTplFn(value) {
        if (value.indexOf('team')==-1) {
            this.show_select = true;
            this.templateFn();
        } else {
            this.show_select = false;
            this.template    = teamHtml;
        } 
    }

    /**
     * 根据分类获取相应的数据
     * @param  {[type]} genderby [description]
     * @return {[type]}          [description]
     */
    realtimeFn(genderby) {

        var course_id = this.course.course_id,
            genderby  = genderby || 'all',
            search    = this.$state.params.race_id + '&course_id=' + course_id + '&genderby=' + genderby;

        var params = {
            action: 'realtime',
            name: 'dashboard.race.realtimerunner',
            id: 'runner_id'
        }

        // 初始化表格控件, ajax请求数据 单程/自定义    
        if (this.course.course_type == 'oneway' || this.course.course_type == 'custom') {
            this.tableService.getPersonOnewayList(params, this.$cookieStore.get('access_token'), search);
        }

        // 初始化表格控件, ajax请求数据 绕圈
        if (this.course.course_type == 'circle') {
            this.tableService.getPersonCircleList(params, this.$cookieStore.get('access_token'), search);
        }
    }

    /**
     * 团队实时成绩
     * @param  {[type]} genderby [description]
     * @return {[type]}          [description]
     */
    distTeamFn(genderby) {

        var course_id = this.course.course_id,
            race_id   = this.$state.params.race_id,
            type      = genderby || 'all',
            search    = course_id + '&race_id=' + race_id + '&type=' + type;

        this.ScoreService.getRealtimeTeam(this.$cookieStore.get('access_token'), search)
        .then( data => {

            // 成功调用
            (data.code==0) && (this.teamlist = data.data.scores);

            //保存事实页面数据用于打印
            this.$rootScope.realtimeData = {
                type:  'team',
                list: data.data.scores
            };            
            // 调用失败, 提示用户
            (data.code!=0&&data.code!=-1001) && this.dialogService.error(data.message);

            // 登录信息已过期, 请重新登录
            (data.code==-1001) && this.dialogService.error(data.message, true);

            console.log(data)
        }, error => console.log('error'))
    }
    

    /**
     * 按CP点搜索
     * @param  {[type]} cp_index [description]
     * @return {[type]}          [description]
     */
    tableSearchFn(cp_index) {

        if (cp_index == 0) {
            $('#person_table').DataTable().search(0).draw();
        } else {
            $('#person_table').DataTable().search(cp_index || '').draw();
        }

    }

}

RealtimeListController.$inject = ['$rootScope', '$scope', '$cookieStore', '$timeout', '$state', '$filter', 'ngDialog', 'tableService', 'dialogService', 'ScoreService', 'getRaceDetail', 'getCourseList', 'iRunner']; 

export default RealtimeListController;